/**
 * @file exti.c
 * @brief  exti驱动程序（基于STM32的v3.5库）
 * @author 王晓荣
 * @version 
 * @date 2014-03-22
 */

#include "led.h"
#include "exti.h"

 

static const struct EXTI_PIN exti_pin[] = 
{
    {{GPIOA, 0 }, {EXTI_Trigger_Rising, 3, 0}},
    {{GPIOC, 13}, {EXTI_Trigger_Falling, 3, 1}},    
};

static uint8_t exti0_flg  = 0;
static uint8_t exti13_flg = 0;

static const IRQn_Type irq_tab[] =
{
    EXTI0_IRQn,     EXTI1_IRQn,     EXTI2_IRQn,     EXTI3_IRQn,   EXTI4_IRQn, 
    EXTI9_5_IRQn,   EXTI9_5_IRQn,   EXTI9_5_IRQn,   EXTI9_5_IRQn, EXTI9_5_IRQn, 
    EXTI15_10_IRQn, EXTI15_10_IRQn, EXTI15_10_IRQn, 
    EXTI15_10_IRQn, EXTI15_10_IRQn, EXTI15_10_IRQn, 
};


#define NUM_EXTIS (sizeof(exti_pin)/sizeof(struct EXTI_PIN))


/**
 * @brief 外部中断配置
 */
void exti_config (void) 
{
    uint8_t          n;
    uint8_t          priority;
    GPIO_InitTypeDef GPIO_InitStructure;
    EXTI_InitTypeDef EXTI_InitStructure;
    NVIC_InitTypeDef         NVIC_InitStructure;  

    gpio_clock_afio_enable();    
    
    for (n = 0; n < NUM_EXTIS; n++) 
    {      
        gpio_clock_enable(exti_pin[n].gpio_pin.port);    
        
        GPIO_InitStructure.GPIO_Pin   = exti_pin[n].gpio_pin.pin;  
        GPIO_InitStructure.GPIO_Speed = GPIO_Speed_2MHz;
        GPIO_InitStructure.GPIO_Mode  = GPIO_Mode_IPU;
        GPIO_Init(exti_pin[n].gpio_pin.port, &GPIO_InitStructure);  

        GPIO_EXTILineConfig(((exti_pin[n].gpio_pin.port - GPIOA) >> 2) / 9, 
                             exti_pin[n].gpio_pin.pin );         

        EXTI_InitStructure.EXTI_Line    = 1 << exti_pin[n].gpio_pin.pin;		 
        EXTI_InitStructure.EXTI_Mode    = EXTI_Mode_Interrupt;
        EXTI_InitStructure.EXTI_Trigger = exti_pin[n].exti.trigger;  
        EXTI_InitStructure.EXTI_LineCmd = ENABLE;
        EXTI_Init(&EXTI_InitStructure);
        
        NVIC_EnableIRQ(irq_tab[exti_pin[n].gpio_pin.pin]);     //  Enable External Interrupt
        priority = NVIC_EncodePriority(5,
                                       exti_pin[n].exti.PreemptPriority,
                                       exti_pin[n].exti.SubPriority      ); 
        NVIC_SetPriority(irq_tab[exti_pin[n].gpio_pin.pin],priority); //Set Interrupt Priority  
        
        NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0;
        NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
        NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;		
        NVIC_Init(&NVIC_InitStructure);	
               
    }      
}

uint8_t read_exti0_flg(void)
{
    return exti0_flg;
}  

uint8_t read_exti13_flg(void)
{
    return exti13_flg;
}

void clr_exti0_flg(void)
{
    exti0_flg = 0;
}

void clr_exti13_flg(void)
{
    exti13_flg = 0;
}


/**
 * @brief EXTI0中断函数
 */
void EXTI0_IRQHandler(void)
{
    exti0_flg = 1;
	
	EXTI_ClearITPendingBit(EXTI_Line0);	
} 

/**
 * @brief EXTI15_10中断函数
 */
void EXTI15_10_IRQHandler(void)
{
    exti13_flg = 1;
	
	EXTI_ClearITPendingBit(EXTI_Line13);	
} 


